import java.util.regex.Pattern as Pattern

# Filter processing should continue with the next filter in the sequence
FILTER_CONTINUE = 1

# Filter processing should stop immediately; the text is as good as it can be
FILTER_CONCLUDE = 2

# The entire body of the text should be ignored
FILTER_IGNORE   = 3

class SchmuckAnsiFilter(object):
	def __init__(self):
		self.regular_expression = Pattern.compile("(\x1b\[[0-9;]+m)")

	def filter_text(self, socket_id, text):
		newtext = []
		for style, string in text:
			if(style == "regular"):
				match = self.regular_expression.matcher(string)
				start = 0
				current_style = "regular"
				while(match.find()):
					newtext.append((current_style, string[start:match.start()]))
					codes = string[match.start()+2:match.end()-1]
					for code in codes.split(';'):
						if(code == '0'):
							current_style = "regular"
						if(code == '1'):
							current_style = "bold"
						if(code == '3' or code == '5'):
							current_style = "italic"
						if(code == '4' or code == '5'):
							current_style = "underline"
						if(len(code) == 2 and code[0] == '3'):
							pass	# TODO: color support
					start = match.end()
				newtext.append((current_style, string[start:]))
			else:
				newtext.append((style, string))
		return [FILTER_CONTINUE, newtext]

class SchmuckTextFilter(object):
	def __init__(self):
		self.filterlist = []
		
	def add_filter(self, filter):
		self.filterlist.insert(0, filter)
		
	def filter_text(self, socket_id, text):
		# Convert text to an array
		text = [("regular", text)]
		for filter in self.filterlist:
			try:
				result, text = filter.filter_text(socket_id, text)
				if(result == FILTER_CONCLUDE):
					break
				elif (result == FILTER_IGNORE):
					return
			except Exception, ex:
				print ex 
		return text
		
schmuck_text_filters["ansi"] = SchmuckAnsiFilter()